package com.zmn.oms.zmn.business.impl.redistribute;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zmn.anole.dubbo.interfaces.AnoleRemoteService;
import com.zmn.base.product.common.consts.BaseProductConsts;
import com.zmn.base.product.common.consts.DubboConsts;
import com.zmn.base.product.common.dto.categ.CategProductGroupDRO;
import com.zmn.base.product.common.dto.product.ProductBaseQuery;
import com.zmn.base.product.common.dto.product.ec.ProductBaseDRO;
import com.zmn.base.product.common.query.categ.CategProductGroupQuery;
import com.zmn.base.product.dubbo.interfaces.categ.serv.CategServProductListRemoteService;
import com.zmn.biz.abnormal.common.dro.AbnormalCategDRO;
import com.zmn.biz.abnormal.dubbo.interfaces.AbnormalListRemoteService;
import com.zmn.biz.complain.common.dro.complain.ChsComplainSimpleDRO;
import com.zmn.biz.complain.dubbo.interfaces.complain.ChsComplainApiListRemoteService;
import com.zmn.base.product.dubbo.interfaces.product.foreign.ProductForeignListRemoteService;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.consts.GlobalConsts;
import com.zmn.manager.mq.interfaces.ZmnMQSender;
import com.zmn.oms.business.interfaces.es.OrderWorkEsBService;
import com.zmn.oms.business.interfaces.log.OrderRedistributeLogBService;
import com.zmn.oms.business.interfaces.order.DuplicateOrderBService;
import com.zmn.oms.business.interfaces.work.OrderWorkListBService;
import com.zmn.oms.common.annotation.OrderWorkRedistributeLog;
import com.zmn.oms.common.constant.*;
import com.zmn.oms.common.dio.redistribute.DoingDuplicateOrderDIO;
import com.zmn.oms.common.dio.redistribute.RedistributeServingDuplicateOrderDIO;
import com.zmn.oms.common.enums.ConfRedistributeAuditTypeEnum;
import com.zmn.oms.common.enums.RedistributeAuditStatusEnum;
import com.zmn.oms.common.enums.RedistributeHelpStatusEnum;
import com.zmn.oms.common.enums.RedistributeStatusEnum;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.common.utils.HttpUtil;
import com.zmn.oms.common.utils.MobileUtil;
import com.zmn.oms.constant.MessageQueueTopicConstant;
import com.zmn.oms.model.bo.work.redistribute.OrderWorkRedistributeModifyBO;
import com.zmn.oms.model.dto.log.OrderRedistributeLogQuery;
import com.zmn.oms.model.dto.redistribute.RedistributeAttachmentDTO;
import com.zmn.oms.model.entity.changerecord.OrderChangeRecord;
import com.zmn.oms.model.entity.conf.distributereason.ConfOrderDistributeReason;
import com.zmn.oms.model.entity.conf.distributereason.ConfOrderDistributeReasonQuery;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.log.OrderRedistributeLog;
import com.zmn.oms.model.entity.product.OrderProductExtend;
import com.zmn.oms.model.entity.redistribute.OrderWorkRedistributeApply;
import com.zmn.oms.model.entity.serviceitem.OrderServiceItem;
import com.zmn.oms.model.entity.serviceitem.OrderServiceItemCell;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.query.redistribute.OrderWorkRedistributeExport;
import com.zmn.oms.model.query.redistribute.OrderWorkRedistributeQuery;
import com.zmn.oms.model.vo.changerecord.ZsOrderChangeRecordVO;
import com.zmn.oms.model.vo.redistribute.OrderWorkRedistributeInfoVO;
import com.zmn.oms.model.vo.redistribute.OrderWorkRedistributeMasterVO;
import com.zmn.oms.model.vo.work.ZsOrderDistributeVO;
import com.zmn.oms.model.vo.work.detail.*;
import com.zmn.oms.services.interfaces.changerecord.OrderChangeRecordService;
import com.zmn.oms.services.interfaces.conf.distributereason.ConfOrderDistributeReasonService;
import com.zmn.oms.services.interfaces.detail.OrderDetailService;
import com.zmn.oms.services.interfaces.product.OrderProductExtendService;
import com.zmn.oms.services.interfaces.redistribute.OrderWorkRedistributeApplyService;
import com.zmn.oms.services.interfaces.redistribute.OrderWorkRedistributeInfoService;
import com.zmn.oms.services.interfaces.serviceitem.OrderServiceItemService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.zmn.business.interfaces.redistribute.OrderWorkRedistributeInfoBService;
import com.zmn.oms.zmn.business.interfaces.work.customwork.ZsDistributeWorkBService;
import com.zmn.pay.common.constant.PayConsts;
import com.zmn.tapi.common.export.model.dio.AddExportTaskDIO;
import com.zmn.tapi.common.export.model.dio.ExportHttpDIO;
import com.zmn.tapi.common.export.model.dio.SheetDIO;
import com.zmn.tapi.dubbo.interfaces.export.ExportModifyRemoteService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.Reference;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.query.FetchSourceFilter;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 类描述: 工单改派信息 业务逻辑处理类
 *
 * @author: liudi
 * @since: 2022/05/11 14:00
 */
@Slf4j
@Service
public class OrderWorkRedistributeInfoBServiceImpl implements OrderWorkRedistributeInfoBService {

	/**
	 * 导出文件名称
	 */
	public static final String ORDER_FILE_NAME = "改派管理";

	/**
	 * 导出类型
	 */
	public static final String EXPORT_TYPE = "改派列表";

	/**
	 * 导出文件类型
	 */
	public static final String EXPORT_FILE_TYPE = ".xlsx";

	/**
	 * sheet1名称
	 */
	public static final String ORDER_SHEET_ONE_NAME = "改派信息";

	/**
	 * sheet1的列数
	 */
	private static int sheetOneSize = 23;

	private static List<String> sheetOneFirstRowList = Lists.newArrayListWithCapacity(sheetOneSize);

	static {
		sheetOneFirstRowList.add("发起时间");
		sheetOneFirstRowList.add("下单时间");
		sheetOneFirstRowList.add("发起人");
		sheetOneFirstRowList.add("工单号");
		sheetOneFirstRowList.add("子公司");
		sheetOneFirstRowList.add("产品组");
		sheetOneFirstRowList.add("申请的改派缘由");
		sheetOneFirstRowList.add("核实的改派缘由");
		sheetOneFirstRowList.add("工单状态");
		sheetOneFirstRowList.add("审核状态");
		sheetOneFirstRowList.add("改派状态");
		sheetOneFirstRowList.add("主工程师");
		sheetOneFirstRowList.add("改派后主工程师");
		sheetOneFirstRowList.add("审核人");
		sheetOneFirstRowList.add("审核人类型");
		sheetOneFirstRowList.add("改派审核预警");
		sheetOneFirstRowList.add("改派审核超时");
		sheetOneFirstRowList.add("转单求助超时");
		sheetOneFirstRowList.add("是否虚假");
		sheetOneFirstRowList.add("计入轮次");
		sheetOneFirstRowList.add("最后一次更新人");
		sheetOneFirstRowList.add("最后一次更新时间");
		sheetOneFirstRowList.add("改派次数");
	}

	// tapi导出服务地址
	@Value("${zmn.tapi.export.url:http://test2-tapi.xiujiadian.com/api/export/exportMultipleSheetInfo}")
	private String ZMN_TAPI_EXPORT_URL;

	@Resource
	private ZmnMQSender zmnMQSender;
	@Resource
	private OrderWorkService orderWorkService;
	@Resource
	private OrderDetailService orderDetailService;
	@Resource
	private OrderWorkEsBService orderWorkEsBService;
	@Resource
	private OrderWorkListBService orderWorkListBService;
	@Resource
	private OrderServiceItemService orderServiceItemService;
	@Resource
	private ZsDistributeWorkBService zsDistributeWorkBService;
	@Resource
	private OrderChangeRecordService orderChangeRecordService;
	@Resource
	private OrderProductExtendService orderProductExtendService;
	@Resource
	private OrderRedistributeLogBService orderRedistributeLogBService;
	@Resource
	private OrderWorkRedistributeInfoService orderWorkRedistributeInfoService;
	@Resource
	private OrderWorkRedistributeApplyService orderWorkRedistributeApplyService;
	@Resource
	private ConfOrderDistributeReasonService confOrderDistributeReasonService;
	@Autowired
	private DuplicateOrderBService duplicateOrderBService;

	@Reference(version = com.zmn.anole.dubbo.interfaces.AnoleRemoteService.VERSION, check = false)
	private AnoleRemoteService anoleRemoteService;
	@DubboReference(version = com.zmn.biz.abnormal.common.constant.DubboConsts.INTERFACE_VERSION, check = false)
	private AbnormalListRemoteService abnormalListRemoteService;
	@DubboReference(version = com.zmn.tapi.dubbo.DubboConsts.INTERFACE_VERSION, check = false)
	private ExportModifyRemoteService exportModifyRemoteService;
	@DubboReference(version = com.zmn.biz.complain.common.constant.DubboConsts.INTERFACE_VERSION, check = false)
	private ChsComplainApiListRemoteService chsComplainApiListRemoteService;
	@DubboReference(version = com.zmn.base.product.common.consts.DubboConsts.INTERFACE_VERSION , check = false)
	private CategServProductListRemoteService categServProductListRemoteService;
	@DubboReference(version = DubboConsts.INTERFACE_VERSION, check = false)
	private ProductForeignListRemoteService productForeignListRemoteService;


	@Override
	public OrderWorkRedistributeInfoVO getRedistributeInfoVOById(Long redistributeId) {
		Objects.requireNonNull(redistributeId, "改派ID不能为空！");

		OrderWorkRedistributeInfoVO infoVO = orderWorkRedistributeInfoService.findApplyInfoByRedistributeId(redistributeId);
		if (Objects.isNull(infoVO)) {
			return new OrderWorkRedistributeInfoVO();
		}

		// 处理改派信息
		this.processRedistributeInfoVO(infoVO);

		return infoVO;
	}


	@Override
	public List<OrderWorkRedistributeInfoVO> listPageByQuery(OrderWorkRedistributeQuery query) {
		// 处理查询条件
		this.processQuery(query);

		// 查询 改派申请 信息
		List<OrderWorkRedistributeInfoVO> infoList = orderWorkRedistributeInfoService.listPageByQuery(query);

		if (CollectionUtils.isEmpty(infoList)) {
			return Lists.newArrayList();
		}

		infoList.forEach(infoVO -> {
			// 将状态转换成对应的名称
			this.processStatusToName(infoVO);
		});

		return infoList;
	}

	@Override
	public void buildExportTask(OrderWorkRedistributeQuery query) throws OmsBaseException {
		AddExportTaskDIO addExportTaskDIO = AddExportTaskDIO.builder()
				.exportType(EXPORT_TYPE)
				.exportName(ORDER_FILE_NAME)
				.fileType(EXPORT_FILE_TYPE)
				.staffId(query.getStaffId())
				.creater(query.getOperator())
				.build();
		ResponseDTO<Integer> responseDTO = exportModifyRemoteService.addExportTask(addExportTaskDIO);
		if (!responseDTO.isSuccess() || Objects.isNull(responseDTO.getData())) {
			throw new OmsBaseException("导出失败");
		}

		Integer exportTaskId = responseDTO.getData();
		query.setExportTaskId(exportTaskId);
		String json = JSON.toJSONString(query);
		String key = String.format("%s-%s", StringUtil.getRandomStringAndNumber3(26), exportTaskId);
		log.debug("异步导出改派列表key：【{}】", key);
		zmnMQSender.send(MessageQueueTopicConstant.ZMN_TOPIC_OMS, MessageQueueTagConsts.REDISTRIBUTE_APPLY_ASYNC_EXPORT, key, json);
	}

	@Override
	public void asyncExportListRedistributeByQuery(OrderWorkRedistributeQuery query) {
		ResponseDTO<String> exportToken = exportModifyRemoteService.getExportToken(query.getExportTaskId());
		if (!exportToken.isSuccess() || Objects.isNull(exportToken.getData())) {
			log.info("异步导出获取Token失败，taskId={}", query.getExportTaskId());
			return;
		}

		List<OrderWorkRedistributeExport> orderRedistributeExportList = orderWorkRedistributeInfoService.asyncExportListRedistributeByQuery(query);

		// 改派缘由map
		Map<Integer, String> redistributeReasonMap  = Maps.newHashMap();
		if (CollectionUtils.isNotEmpty(orderRedistributeExportList)){
			redistributeReasonMap = confOrderDistributeReasonService.listByQuery(new ConfOrderDistributeReasonQuery()).stream()
					.collect(Collectors.toMap(ConfOrderDistributeReason::getId, ConfOrderDistributeReason::getReason));
		}

		List<SheetDIO> sheetDIOList = Lists.newArrayListWithCapacity(1);
		SheetDIO sheetOne = SheetDIO.builder()
				.sheetName(ORDER_SHEET_ONE_NAME)
				.build();
		List<List<String>> sheetOneList = Lists.newArrayListWithCapacity(orderRedistributeExportList.size() + 1);

		// 表头
		sheetOneList.add(sheetOneFirstRowList);

		// 表格内容
		for (OrderWorkRedistributeExport redistributeExport : orderRedistributeExportList) {
			List<String> sheetOneRowList = Lists.newArrayListWithCapacity(sheetOneSize);
			sheetOneRowList.add(DateUtil.toString(redistributeExport.getCreateTime()));
			sheetOneRowList.add(DateUtil.toString(redistributeExport.getReceiveTime()));
			sheetOneRowList.add(redistributeExport.getApplyUser());
			sheetOneRowList.add(String.valueOf(redistributeExport.getWorkId()));
			sheetOneRowList.add(redistributeExport.getCompanyName());
			sheetOneRowList.add(redistributeExport.getServProductGroupName());
			sheetOneRowList.add(redistributeExport.getReason());
			sheetOneRowList.add(redistributeReasonMap.get(redistributeExport.getAuditReasonId()));
			sheetOneRowList.add(OrderStatusConsts.getWorkStatusName(redistributeExport.getStatus()));
			sheetOneRowList.add(RedistributeAuditStatusEnum.getEnumDesc(redistributeExport.getAuditStatus()));
			sheetOneRowList.add(RedistributeStatusEnum.getEnumDesc(redistributeExport.getRedistributeStatus()));
			sheetOneRowList.add(redistributeExport.getMasterName());
			sheetOneRowList.add(redistributeExport.getRedistributeMasterName());
			sheetOneRowList.add(redistributeExport.getAuditer());
			sheetOneRowList.add(ConfRedistributeAuditTypeEnum.getNameByType(redistributeExport.getAuditerType()));
			sheetOneRowList.add(Objects.equals(redistributeExport.getAuditWarningStatus(), GlobalConsts.YES) ? "是" : "否");
			sheetOneRowList.add(Objects.equals(redistributeExport.getAuditTimeoutStatus(), GlobalConsts.YES) ? "是" : "否");
			sheetOneRowList.add(Objects.equals(redistributeExport.getHelpTimeoutStatus(), GlobalConsts.YES) ? "是" : "否");

			String spuriousStatusName = "";
			if (StringUtils.isNotBlank(redistributeExport.getAuditer())) {
				spuriousStatusName = Objects.equals(redistributeExport.getSpuriousStatus(), GlobalConsts.YES) ? "是" : "否";
			}

			sheetOneRowList.add(spuriousStatusName);
			sheetOneRowList.add(Objects.equals(redistributeExport.getCountEnable(), GlobalConsts.YES) ? "是" : "否");
			sheetOneRowList.add(redistributeExport.getUpdater());
			sheetOneRowList.add(DateUtil.toString(redistributeExport.getUpdateTime()));
			Integer distributeCount = NumberUtil.isNullOrZero(redistributeExport.getDistributeCount()) ? 0 : redistributeExport.getDistributeCount();
			sheetOneRowList.add(String.valueOf(distributeCount));
			sheetOneList.add(sheetOneRowList);
		}

		sheetOne.setExportContents(sheetOneList);
		sheetDIOList.add(sheetOne);

		ExportHttpDIO exportHttpDIO = new ExportHttpDIO();
		exportHttpDIO.setExportTaskId(query.getExportTaskId());
		exportHttpDIO.setToken(exportToken.getData());
		exportHttpDIO.setList(sheetDIOList);
		try {
			log.debug("[{}]异步导出改派列表入参：【{}】", query.getExportTaskId(), JSON.toJSONString(exportHttpDIO));
			String response = HttpUtil.httpsPost(ZMN_TAPI_EXPORT_URL, JSON.toJSONString(exportHttpDIO));
			log.info("异步导出改派列表出参，taskId={}，【{}】", query.getExportTaskId(), response);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("异步导出改派列表失败：taskId=【{}】失败信息：【{}】", query.getExportTaskId(), e.getMessage());
		}
	}


	@Override
	public List<OrderWorkRedistributeMasterVO> listRedistributeEngineer(Long orderId, Long workId) {
		OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);
		OrderDetail orderDetail = orderDetailService.findOrderDetailByKey(orderId);

		List<ZsOrderDistributeVO> zsOrderDistributeVOList = zsDistributeWorkBService.getRedistributeMasterList(orderWork, orderDetail);
		if (CollectionUtils.isEmpty(zsOrderDistributeVOList)) {
			return Lists.newArrayList();
		}

		return zsOrderDistributeVOList.stream()
				.filter(r -> !Objects.equals(r.getMasterId(), orderWork.getMasterId()))
				.map(m -> {
					OrderWorkRedistributeMasterVO masterVO = BeanMapper.map(m, OrderWorkRedistributeMasterVO.class);
					// 加密工程师手机号
					masterVO.setMasterPhone(MobileUtil.formatHideTel(masterVO.getMasterPhone()));
					return masterVO;
				})
				.collect(Collectors.toList());
	}


	@Override
	public Boolean checkServingDuplicateOrder(RedistributeServingDuplicateOrderDIO dio) {
		try {
			OrderWork orderWork = orderWorkService.findOrderWorkByKey(dio.getOrderId(), dio.getWorkId());
			// 只处理新单
			if (!Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_NEW)) {
				return false;
			}
			OrderDetail orderDetail = orderDetailService.findOrderDetailByKey(dio.getOrderId());
			// 三个电话 任一电话匹配
			List<String> phoneList = Lists.newArrayList(orderDetail.getTelephone());
			if (StringUtils.isNotBlank(orderDetail.getTelephone2())) {
				phoneList.add(orderDetail.getTelephone2());
			}
			if (StringUtils.isNotBlank(orderDetail.getTelephone3())) {
				phoneList.add(orderDetail.getTelephone3());
			}
			// 经度纬度
			Double latitude = dio.getLatitude();
			Double longitude = dio.getLongitude();
			if (latitude == null || longitude == null) {
				latitude = orderDetail.getLatitude();
				longitude = orderDetail.getLongitude();
			}

			// 产品组ID
			Integer servProductGroupId = getServProductGroupId(dio, orderWork);

			DoingDuplicateOrderDIO doingDuplicateOrderDIO = new DoingDuplicateOrderDIO();
			doingDuplicateOrderDIO.setWorkId(dio.getWorkId());
			doingDuplicateOrderDIO.setPhoneList(phoneList);
			doingDuplicateOrderDIO.setServProductGroupId(servProductGroupId);
			doingDuplicateOrderDIO.setLatitude(latitude);
			doingDuplicateOrderDIO.setLongitude(longitude);
			Long doingDuplicateOrderId = duplicateOrderBService.findDoingDuplicateOrderId(doingDuplicateOrderDIO);
			return Objects.nonNull(doingDuplicateOrderId);
		} catch (Exception e) {
			log.error("检查在途重复时发生异常：[{}]", e.getMessage());
		}
		return Boolean.FALSE;
	}

	/**
	 *  获取产品分组ID
	 * @param dio
	 * @param orderWork
	 * @return
	 */
	private Integer getServProductGroupId(RedistributeServingDuplicateOrderDIO dio, OrderWork orderWork) {
		Integer servProductGroupId = dio.getServProductGroupId();
		if (NumberUtil.isNotNullOrZero(servProductGroupId)) {
			return servProductGroupId;
		}

		if (!NumberUtil.isNullOrZero(dio.getProductId())) {
			ProductBaseQuery productBaseQuery = ProductBaseQuery.builder()
					.productId(dio.getProductId())
					.showType(BaseProductConsts.ERP_SHOW_TYPE)
					.build();
			ResponseDTO<List<ProductBaseDRO>> listResponseDTO = productForeignListRemoteService.listBaseDROByQuery(productBaseQuery);
			if (Objects.nonNull(listResponseDTO) && CollectionUtil.isNotNullOrEmpty(listResponseDTO.getData())) {
				ProductBaseDRO productBaseDRO = listResponseDTO.getData().get(0);
				dio.setServCategId(productBaseDRO.getServCategId());
				dio.setCategId(productBaseDRO.getCategId());
			}
		}

		if (NumberUtil.isNullOrZero(dio.getServCategId()) || NumberUtil.isNullOrZero(dio.getCategId())) {
			return orderWork.getServProductGroupId();
		}

		// 后台产品分组
		if (log.isDebugEnabled()) {
			log.debug("categServProductListRemoteService#getProductGroupByCategId 查询产品分组 入参：" +
					"servCategId={}, categId={}", dio.getServCategId(), dio.getCategId());
		}
		CategProductGroupQuery categProductGroupQuery = new CategProductGroupQuery();
		categProductGroupQuery.setBizType(orderWork.getBizType());
		categProductGroupQuery.setServCategId(dio.getServCategId());
		categProductGroupQuery.setCategId(dio.getCategId());
		categProductGroupQuery.setShowType(BaseProductConsts.ERP_SHOW_TYPE);
		ResponseDTO<CategProductGroupDRO> categoryProductGroupDROResponseDTO = categServProductListRemoteService
				.getBasisProductGroupByQuery(categProductGroupQuery);
		if (log.isDebugEnabled()) {
			log.debug("categServProductListRemoteService#getProductGroupByCategId 查询产品分组 出参：【{}】",
					categoryProductGroupDROResponseDTO);
		}
		if (Objects.nonNull(categoryProductGroupDROResponseDTO) && Objects.nonNull(categoryProductGroupDROResponseDTO.getData())) {
			return categoryProductGroupDROResponseDTO.getData().getGroupId();
		}
		return orderWork.getServProductGroupId();
	}

	@Override
	@OrderWorkRedistributeLog(type = OrderWorkRedistributeLogConsts.ORDER_REDISTRIBUTE_LOG_TYPE_ADD_NOTE, beforeProceed = false)
	public void addRemark(OrderWorkRedistributeModifyBO modityBO) throws OmsBaseException {
		OrderWorkRedistributeApply dbRedistributeApply = orderWorkRedistributeApplyService.selectByPrimaryKey(modityBO.getRedistributeId());

		// 状态为 待改派 并且是 （待审核 或者 处理中）才可以改备注
		if (Objects.isNull(dbRedistributeApply)
				|| !Objects.equals(dbRedistributeApply.getRedistributeStatus(), RedistributeStatusEnum.WAIT_REDISTRIBUTE.getCode())) {
			throw new OmsBaseException("该改派申请不存在或已完结，无需添加备注！");
		}

		if (!(Objects.equals(dbRedistributeApply.getAuditStatus(), RedistributeAuditStatusEnum.WAIT_AUDIT.getCode())
				|| Objects.equals(dbRedistributeApply.getAuditStatus(), RedistributeAuditStatusEnum.PROCESSING_AUDIT.getCode()))) {
			throw new OmsBaseException("该改派申请已审核或无需审核，无需添加备注！");
		}

		// 修改状态为进行中
		OrderWorkRedistributeApply apply = BeanMapper.map(modityBO, OrderWorkRedistributeApply.class);
		apply.setAuditStatus(RedistributeAuditStatusEnum.PROCESSING_AUDIT.getCode());
		orderWorkRedistributeApplyService.updateByPrimaryKeySelective(apply);
	}

	/**
	 * 处理查询条件
	 *
	 * @param
	 * @return
	 */
	private void processQuery(OrderWorkRedistributeQuery query) {

		// 当 没有加密后的手机号 且 有用户手机号时才去解密
		if (StringUtils.isBlank(query.getCryptoPhone()) && StringUtils.isNotBlank(query.getConcatPhone())) {
			// 加密手机号
			ResponseDTO<String> responseDTO = anoleRemoteService.encrypt(query.getConcatPhone());
			if (responseDTO.isSuccess()) {
				query.setConcatPhone(responseDTO.getData());
			}
		} else {
			query.setConcatPhone(query.getCryptoPhone());
		}
	}

	/**
	 * 处理改派详情信息
	 *
	 * @param infoVO
	 * @return
	 */
	private void processRedistributeInfoVO(OrderWorkRedistributeInfoVO infoVO) {
		Long orderId = infoVO.getOrderId();
		Long workId = infoVO.getWorkId();
		OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);
		OrderDetail orderDetail = orderDetailService.findOrderDetailByKey(orderId);

		// 使用订单的地址进行展示
		if (Objects.nonNull(orderDetail)) {
			infoVO.setOrderDetail(orderDetail);
		}

		// 解密及加密展示在页面的手机号
		if (StringUtil.isNotBlank(infoVO.getMasterPhone())
				|| StringUtil.isNotBlank(infoVO.getTelephone())
				|| StringUtil.isNotBlank(infoVO.getTelephone2())
				|| StringUtil.isNotBlank(infoVO.getTelephone3())) {

			// 解密工程师手机号
			if (StringUtils.isNotBlank(infoVO.getMasterPhone())) {
				infoVO.setMasterPhone(MobileUtil.formatHideTel(infoVO.getMasterPhone()));
			}

			Map<String, String> telephoneMap = Maps.newHashMap();

			// 加密用户手机号
			if (StringUtils.isNotBlank(infoVO.getTelephone())) {
				telephoneMap.put("1", MobileUtil.formatHideTel(infoVO.getTelephone()));
			}
			if (StringUtils.isNotBlank(infoVO.getTelephone2())) {
				telephoneMap.put("2", MobileUtil.formatHideTel(infoVO.getTelephone2()));
			}
			if (StringUtils.isNotBlank(infoVO.getTelephone3())) {
				telephoneMap.put("3", MobileUtil.formatHideTel(infoVO.getTelephone3()));
			}

			infoVO.setTelephoneMap(telephoneMap);
		}

		// 改派次数、改约次数
		OrderChangeRecord changeRecord = orderChangeRecordService.getChangeRecordByOrderId(orderId);
		if (Objects.nonNull(changeRecord)) {
			ZsOrderChangeRecordVO changeRecordVO = BeanMapper.map(changeRecord, ZsOrderChangeRecordVO.class);
			infoVO.setDutyTimeModifyCount(changeRecordVO.getDutyTimeModifyCount());
			infoVO.setDistributeCount(changeRecordVO.getDistributeCount());
		}

		// 查询产品服务项
		List<OrderProductExtend> orderProductExtendList = orderProductExtendService.listByOrderId(orderId);
		Map<Long, OrderProductExtend> orderProductMap = orderProductExtendList.stream()
				.collect(Collectors.toConcurrentMap(OrderProductExtend::getProExtId, orderProduct -> orderProduct));
		List<OrderServiceItem> orderServiceItemList = orderServiceItemService.listByOrderId(orderId);

		if (!orderServiceItemList.isEmpty()) {
			List<ZsOrderWorkDetailProductVO> serviceItemVoList = Lists.newArrayList();
			Map<Long, List<OrderServiceItem>> serviceItemMap = orderServiceItemList.stream()
					.collect(Collectors.groupingBy(OrderServiceItem::getProExtId));

			serviceItemMap.forEach((key, value) -> {
				OrderProductExtend orderProduct = orderProductMap.get(key);
				Integer totalAmount = 0;
				List<ZsOrderWorkDetailServiceItemVO> serviceItemVOList = Lists.newArrayList();

				for (OrderServiceItem serviceItem : value) {
					ZsOrderWorkDetailServiceItemVO serviceItemVO = new ZsOrderWorkDetailServiceItemVO();

					// 复制服务项明细相关的数据
					if (CollectionUtil.isNotNullOrEmpty(serviceItem.getItemDetailList())) {
						List<ZsOrderWorkDetailServiceItemDetailVO> serviceItemDetailVOList = new ArrayList<>(serviceItem.getItemDetailList().size());
						for (OrderServiceItemCell cell : serviceItem.getItemDetailList()) {
							ZsOrderWorkDetailServiceItemDetailVO vo = new ZsOrderWorkDetailServiceItemDetailVO();
							vo.setItemCellName(cell.getItemCellName());
							vo.setCellPrice(cell.getCellPrice());
							serviceItemDetailVOList.add(vo);
						}
						serviceItemVO.setServiceItemDetailVOList(serviceItemDetailVOList);
					}

					Integer totalPrice = serviceItem.getTotalPrice();
					serviceItemVO.setServiceItemName(serviceItem.getServItemName());
					serviceItemVO.setAmount(serviceItem.getTotalPrice());
					serviceItemVO.setNumber(serviceItem.getNumber());
					serviceItemVOList.add(serviceItemVO);

					totalAmount += totalPrice;
				}

				ZsOrderWorkDetailProductVO zsOrderWorkDetailProductVO = new ZsOrderWorkDetailProductVO();
				zsOrderWorkDetailProductVO.setProExtId(orderProduct.getProExtId());
				zsOrderWorkDetailProductVO.setProductName(orderProduct.getProductName());
				zsOrderWorkDetailProductVO.setServiceItemVOList(serviceItemVOList);
				zsOrderWorkDetailProductVO.setServiceItemTotalAmount(totalAmount);
				serviceItemVoList.add(zsOrderWorkDetailProductVO);
			});
			serviceItemVoList.sort(Comparator.comparing(ZsOrderWorkDetailProductVO::getProExtId));
			infoVO.setServiceItemList(serviceItemVoList);
		}

		// 有投诉 才查询
		if (Objects.equals(orderWork.getComplaintStatus(), GlobalConsts.YES)) {
			ResponseDTO<List<ChsComplainSimpleDRO>> complainResponse = chsComplainApiListRemoteService
					.listComplainSimpleByOrderId(orderId);
			if (complainResponse.isSuccess() && CollectionUtil.isNotNullOrEmpty(complainResponse.getData())) {
				List<ChsComplainSimpleDRO> items = complainResponse.getData();
				List<ZsOrderWorkDetailComplaintVO> complaintVOS = BeanMapper
						.mapList(items, ZsOrderWorkDetailComplaintVO.class);
				infoVO.setComplaintVOList(complaintVOS);
			}
		}

		// 有异常才查询
		if (Objects.equals(orderWork.getAbnormalStatus(), GlobalConsts.YES)) {
			try {
				ResponseDTO<List<AbnormalCategDRO>> listResponseDTO = abnormalListRemoteService
						.listAbnormalCategByOrderId(orderId);
				if (listResponseDTO.isSuccess() && !CollectionUtils.isEmpty(listResponseDTO.getData())) {
					List<AbnormalCategDRO> data = listResponseDTO.getData();
					List<ZsOrderWorkDetailAbnormalVO> abnormalVOList = BeanMapper
							.mapList(data, ZsOrderWorkDetailAbnormalVO.class);
					infoVO.setAbnormalVOList(abnormalVOList);
				}
			} catch (Exception ex) {
				log.info("工单号：[{}]，获取【工单异常】时发生意外，message：[{}]。", orderId, ex.getMessage());
			}
		}

		// 改派日志
		OrderRedistributeLogQuery logQuery = new OrderRedistributeLogQuery();
		logQuery.setRedistributeId(infoVO.getRedistributeId());
		List<OrderRedistributeLog> orderLogsByQuery = orderRedistributeLogBService.findOrderLogsByQuery(logQuery);
		// 处理改派申请记录的【操作人】为有【组或者部门】的样子
		orderRedistributeLogBService.processLogStaffDept(orderLogsByQuery);
		// 处理改派log工程师信息
		orderRedistributeLogBService.processOrderLogMaster(orderLogsByQuery, orderWork.getBizType());
		infoVO.setLogList(orderLogsByQuery);

		// 处理 照片、音频、视频
		if (StringUtils.isNotBlank(infoVO.getAttachmentUrls())) {
			try {
				List<String> pictureList = Lists.newArrayListWithCapacity(3);
				List<String> videoList = Lists.newArrayListWithCapacity(3);
				List<String> audioList = Lists.newArrayListWithCapacity(3);
				List<RedistributeAttachmentDTO> attachmentList = JSON.parseArray(infoVO.getAttachmentUrls(), RedistributeAttachmentDTO.class);
				attachmentList.forEach(attachment->{
					if (Objects.equals(attachment.getType(), OrderAttachmentCategoryTypeEnum.PICTURE.getCode())) {
						pictureList.add(attachment.getUrl());
					} else if (Objects.equals(attachment.getType(), OrderAttachmentCategoryTypeEnum.VIDEO.getCode())) {
						videoList.add(attachment.getUrl());
					} else if (Objects.equals(attachment.getType(), OrderAttachmentCategoryTypeEnum.AUDIO.getCode())) {
						audioList.add(attachment.getUrl());
					}
				});

				infoVO.setImageSrc(StringUtil.convertListToStrs(pictureList));
				infoVO.setVideoSrc(StringUtil.convertListToStrs(videoList));
				infoVO.setAudioSrc(StringUtil.convertListToStrs(audioList));
			} catch (Exception e) {
				log.error("处理图音视频发生错误 redistributeId={} attachmentUrls={} message={}",
						infoVO.getRedistributeId(), infoVO.getAttachmentUrls(),e.getMessage());
			}

		}

		// 将状态转换为对应的名称
		this.processStatusToName(infoVO);
	}

	/**
	 * 将状态转换为对应的名称
	 *
	 * @param infoVO
	 * @return
	 */
	private void processStatusToName(OrderWorkRedistributeInfoVO infoVO) {
		// 工单状态
		infoVO.setStatusName(OrderStatusConsts.getWorkStatusName(infoVO.getStatus()));
		// 审核状态
		infoVO.setAuditStatusName(RedistributeAuditStatusEnum.getEnumDesc(infoVO.getAuditStatus()));
		// 审核状态
		infoVO.setHelpStatusName(RedistributeHelpStatusEnum.getNameByType(infoVO.getHelpStatus()));
		// 改派状态
		infoVO.setRedistributeStatusName(RedistributeStatusEnum.getEnumDesc(infoVO.getRedistributeStatus()));
		// 支付状态
		infoVO.setPayStatusName(PayConsts.getPayStatusName(infoVO.getPayStatus()));
	}

}